/**
 * 全局监听请求错误
 */

const { HttpException } = require("@core/http-exception.js")
const env = process.env.NODE_ENV

const catchErr = async (ctx, next) => {
  try {
    // ctx.requestApi = `${ctx.method} ${ctx.path}`
    await next()
  } catch (err) {
    // 判断当前环境
    const isDev = env === 'dev' ? true : false
    // 是否属于已知错误
    const isHttpException = err instanceof HttpException ? true : false
    if (isDev && !isHttpException) {
      ctx.body = {
        msg: '遇到了未知错误',
        errCode: 50200,
        request: `${ctx.method} ${ctx.path}`
      }
      ctx.status = 502
      console.log(err)
    }
    if (isHttpException) {
      ctx.body = {
        msg: err.msg,
        errCode: err.errCode,
        request: `${ctx.method} ${ctx.path}`
      }
      ctx.status = err.code
    } else {
      ctx.body = {
        msg: '遇到了未知错误',
        errCode: 50200,
        request: `${ctx.method} ${ctx.path}`
      }
      ctx.status = 502
    }
  }
}

module.exports = {
  catchErr
}